package com.sddongyun.filter;

import com.alibaba.fastjson.JSONObject;
import com.sddongyun.common.ResponseWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * @author lxt
 */

public class QrpayServletFilter implements Filter {
    @Autowired
    JdbcTemplate jdbcTemplate;
    private org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(QrpayServletFilter.class);
    private static final String DOWMLOAD_FILE = "/base/downloadFile";
 
    private static final String URI ="uri";
 
//    @Autowired
//    RedisService redisService;
 
    /**
     * 超时时间
     */
//    @Value("${authorization.timeout}")
    long timeout;
 
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("QrpayServletFilter----"+((HttpServletRequest) request).getRequestURI());
        ServletRequest requestWrapper = null;
        ResponseWrapper responseWrapper = new ResponseWrapper((HttpServletResponse)response);
        Enumeration<String> names = request.getParameterNames();
        JSONObject endJson = new JSONObject();
        endJson.put(URI,((HttpServletRequest) request).getRequestURI());
        endJson.put("method",((HttpServletRequest) request).getMethod());
        endJson.put("bodyParams" , URLDecoder.decode(((HttpServletRequest) request).getQueryString(),"utf-8"));
        String hisMethod=request.getParameter("soap_method");
        String requestCode=request.getParameter("RequestCode");
        String parameter=URLDecoder.decode(request.getParameter("RequestXML"),"utf-8");
        endJson.put("reqDate",formatDate(new Date()));
        endJson.put("hisMehtod",hisMethod);
        endJson.put("reqCode",requestCode);
        endJson.put("parameter",parameter);
        chain.doFilter(request, responseWrapper);
        //获取返回值
        byte[] content = responseWrapper.getContent();
        //判断是否有值
        if (content.length > 0) {
            String str = new String(content, "UTF-8");
            ServletOutputStream out = response.getOutputStream();
            out.write(content);
            out.flush();
            Matcher matcher= Pattern.compile("<Response>.*?</Response>").matcher(str);
            if(matcher.find()) {
                str = matcher.group(0).toString();
            }
            endJson.put("resStr",str);
            endJson.put("resDate",formatDate(new Date()));
        }else{
            endJson.put("resStr",String.valueOf(((HttpServletResponse) response).getStatus()));
            endJson.put("resDate",formatDate(new Date()));
        }
        jdbcTemplate.update("insert into qrpayserverlog(serverip,url,reqdate,hismethod,reqCode,reqparams,resstr,resdate) VALUES (?,?,?,?,?,?,?,?)",
                "192.168.96.103",
                endJson.get(URI).toString(),
                endJson.get("reqDate").toString(),
                endJson.get("hisMehtod").toString(),
                endJson.get("reqCode").toString(),
                endJson.get("parameter").toString(),
                endJson.get("resStr").toString(),
                endJson.get("resDate").toString()
        );

    }

    public String formatDate(Date date){
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return formatter.format(date);
    }
    @Override
    public void destroy() {
 
    }
}